<template>
  <div class="top-bar">
    <!-- 左侧：面包屑导航（显示当前页面路径） -->
    <div class="breadcrumb">
      <router-link to="/">首页</router-link>
      <span class="separator">/</span>
      <span class="current-page">{{ currentPageName }}</span>
    </div>

    <!-- 右侧：用户信息 + 登出 -->
    <div class="user-area">
      <span class="user-role">[{{ userRole }}]</span>
      <span class="user-name">{{ userName }}</span>
      <button class="logout-btn" @click="handleLogout">登出</button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()
const p = ref('')
// 1. 获取用户信息（假设登录时存储了用户名和角色）
// const userName = ref(localStorage.getItem('userName') || '未知用户')
const userRole = ref(localStorage.getItem('userRole') || 'user')

// 2. 动态显示当前页面名称（根据路由路径匹配）
const currentPageName = computed(() => {
  const pageMap = {
    '/': ' ',
    '/work-order/list': '工单列表',
    '/work-order/dispatch': '工单派单',
    '/customer/list': '客户列表',
    '/provide/list': '供应商列表',
    '/product/type-list': '产品类别',
    '/product/list': '产品列表',
    '/permission': '权限管理',
    '/permission/role': '角色管理',
    '/permission/user': '用户管理',
  };
  const keys = Object.keys(pageMap);
  return pageMap[keys.find(key => {
    if (key.includes(':')) {
      // 动态路由匹配
      const baseKey = key.split('/:')[0];
      return p.value.startsWith(baseKey);
    }
    return key === p.value;
  })]
});

// 3. 登出逻辑：清除状态 + 跳登录页
const handleLogout = () => {
  userStore.logout() // 清除Token和登录状态（Pinia中定义的方法）
  router.push('/login') // 跳转到登录页
}

watch(
  () => router.currentRoute.value.path,
  (newPath) => {
    console.log('路由变化了，新的路径是：', newPath);
    p.value = newPath;
    // 这里可以根据路由变化执行相应的操作
  },
)
</script>

<style scoped>
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  background-color: #ffffff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.breadcrumb {
  font-size: 14px;
  color: #666666;
}
.breadcrumb a {
  color: #409eff;
  text-decoration: none;
}
.separator {
  margin: 0 8px;
  color: #cccccc;
}
.current-page {
  color: #333333;
  font-weight: 500;
}
.user-area {
  display: flex;
  align-items: center;
  gap: 16px;
}
.user-role {
  color: #409eff;
}
</style>
